package cn.qqncn.furniture.controller;

import cn.qqncn.furniture.pojo.domain.Car;
import cn.qqncn.furniture.pojo.domain.User;
import cn.qqncn.furniture.pojo.vo.CarVo;
import cn.qqncn.furniture.service.CarService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * @author zkw
 * @ClassName CartController.java
 * @Description 购物车Controller
 * @createTime 2020年12月22日 20:43:00
 */
@Controller
@RequestMapping("car")
public class CarController {
    @Autowired
    CarService carService;

    ObjectMapper objectMapper = new ObjectMapper();


    //todo 查询购物车，head.js里面的axios的get方法获取当前登录的用户购物车信息
    /**
     * 查询该用户的购物车
     * @param userId
     * @return
     */
    @ResponseBody
    @GetMapping("get")
    public List<CarVo> getCats(Integer userId){
        List<CarVo> list = carService.getCar(userId);
        return list;
    }

    /**
     * 购物车删除功能
     * @param request
     * @param furnitureId
     * @return
     * @throws JsonProcessingException
     */
    @ResponseBody
    @GetMapping("delete")
    public String deleteCar(HttpServletRequest request, Integer furnitureId) throws JsonProcessingException {
        Car car = new Car();
        User user = (User) request.getSession().getAttribute("user");
        car.setUserId(user.getUserId());
        car.setFurnitureId(furnitureId);
        int i = carService.deleteCar(car);
        HashMap<String,Object> map = new HashMap<>();
        if (i>0){
            map.put("code","00000");
        }else{
            map.put("code","B0001");
        }
        return objectMapper.writeValueAsString(map);
    }

    /**
     * 添加购物车
     * @param request
     * @param furnitureId 家具id
     * @param number      数量
     * @return
     */
    @GetMapping("add")
    @ResponseBody
    public String addCart(HttpServletRequest request,Integer furnitureId,Integer number) throws JsonProcessingException {
        HashMap<String,Object> map = new HashMap<>();
        Car cart = new Car();
        User user = (User)request.getSession().getAttribute("user");
        cart.setUserId(user.getUserId());
        cart.setFurnitureId(furnitureId);
        cart.setNumber(number);
        int i = carService.addCart(cart);
        if (i>0)
            map.put("code","00000");
        else
            map.put("code","B0001");
        return objectMapper.writeValueAsString(map);
    }
}
